package com.lvmama.rhino.job.comment;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import net.sf.json.JSONObject;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.mortbay.log.Log;
import org.quartz.JobExecutionContext;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.fastjson.JSON;
import com.lvmama.rhino.job.BaseQuartzJobBean;
import com.lvmama.rhino.pojo.comment.entity.CommentDetail;
import com.lvmama.rhino.pojo.comment.entity.ViewDetail;
import com.lvmama.rhino.service.comment.SaveDataService;
import com.lvmama.rhino.utils.DateUtil;
import com.lvmama.rhino.web.comment.auth.AuthUtil;

/**
 * @author shenlinli
 * @ClassName: SaveViewpointJob
 * @Description: TODO
 * @date 2017年9月4日 下午6:19:19
 */

public class SaveDataByDayJob extends BaseQuartzJobBean  {

	@Autowired
	private SaveDataService saveDataService;

	public void invoke(JobExecutionContext context){
		Date yesterday = DateUtil.getYesterdayYYYYMMDD();
		List<CommentDetail> commentList = saveDataService.queryCommentListByTime(yesterday, yesterday);
		List<ViewDetail> viewpointList = new ArrayList<>();
		List<CommentDetail> updateList = new ArrayList<>();
		if(commentList!= null && commentList.size()>0){
			for (CommentDetail comment : commentList) {
				if(comment.getCommentId()!= null && comment.getProductId()!= null){
					try {
						updateList.add(getSentimentClassifyPost(comment));
						Log.info("updateList" + ":------>" + updateList.size());
						List<ViewDetail>list = getCommentTagPost(comment);
						if (list != null && list.size() > 0) {
							for(ViewDetail detail : list){
								if(detail.getCommentId()!= null && detail.getProductId()!= null && StringUtils.isNotEmpty(detail.getTags())){
									viewpointList.add(detail);
									Log.info("viewpointList" + ":------>" + viewpointList.size());
								}
							}
						}
					} catch (Exception e) {
						e.printStackTrace();
						Log.info("list---->add异常");
					}
				}
			}
			if (updateList.size() > 0 && viewpointList.size() > 0) {
				for (int i = 0; i <= updateList.size() / 5000; i++) {
					Log.info("情感分析update评论");
					int j = (i + 1) * 5000;
					if (j > updateList.size()) {
						j = updateList.size();
					}
					try{
						saveDataService.updateCommentList(updateList.subList(i * 5000,
								j));
					} catch (Exception e) {
						e.printStackTrace();
						Log.info("更新数据库异常");
					}
				}
				for (int m = 0; m <= viewpointList.size() / 1000; m++) {
					Log.info("观点提取insert");
					int n = (m + 1) * 1000;
					if (n > viewpointList.size()) {
						n = viewpointList.size();
					}
					try{
						saveDataService.insertViewList(viewpointList.subList(m * 1000,
							n));
					} catch (Exception e) {
						e.printStackTrace();
						Log.info(yesterday +"插入观点异常");
					}
				}
			}
		}
	}

	/**
	 * @param @param text 评价内容
	 * @param @return
	 * @param @throws Exception 设定文件
	 * @return String 返回类型
	 * @throws
	 * @Title: testPost
	 * @Description: 调百度AI接口获取观点信息
	 */
	public List<ViewDetail> getCommentTagPost(CommentDetail comment)
			throws Exception {
		List<ViewDetail> viewpoints = new ArrayList<ViewDetail>();
		String access_token = AuthUtil.getAuth();
		String url = "https://aip.baidubce.com/rpc/2.0/nlp/v2/comment_tag?access_token="
				+ access_token;
		CloseableHttpClient client = HttpClientBuilder.create().build();
		HttpPost post = new HttpPost(url);
		post.setHeader("Content-type", "application/json");

		JSONObject jo = new JSONObject();
		jo.put("text", comment.getContent());
		jo.put("type", 5);

		StringEntity params = new StringEntity(jo.toString(), "GBK");
		post.setEntity(params);

		HttpResponse response = client.execute(post);
		// response
		HttpEntity entity = response.getEntity();
		String result = EntityUtils.toString(entity, "GBK").trim();
		if (StringUtils.isNotEmpty(result) && null != comment.getProductId() && null != comment.getCommentId()) {
			JSONObject jsonObject = JSONObject.fromObject(result);
			if (jsonObject.get("items") != null) {
				com.alibaba.fastjson.JSONArray jsonArr = JSON
						.parseArray(jsonObject.get("items").toString());
				Iterator<Object> it = jsonArr.iterator();
				while (it.hasNext()) {
					com.alibaba.fastjson.JSONObject ob = (com.alibaba.fastjson.JSONObject) it
							.next();
					/* 保存观点 */
					if (!ob.isEmpty()) {
						String prop = (ob.getString("prop") == null) ? "" : ob
								.getString("prop");
						String adj = (ob.getString("adj") == null) ? "" : ob
								.getString("adj");
						ViewDetail viewPoint = new ViewDetail();
						viewPoint
								.setProductId(comment.getProductId());
						viewPoint
								.setCommentId(comment.getCommentId());
						viewPoint.setSentiment(ob.getInteger("sentiment").intValue());
						viewPoint.setProp(prop);
						viewPoint.setAdj(adj);
						viewPoint.setTags(prop + adj);
						if(comment.getProductId().longValue() != 0 && comment.getCommentId().longValue() != 0 ){
							viewpoints.add(viewPoint);
						}
					}
				}
			}
			return viewpoints;
		}else{
			return null;
		}
	}

	/**
	 * @param @param text
	 * @param @return
	 * @param @throws Exception 设定文件
	 * @return void 返回类型
	 * @throws
	 * @Title: getSentimentClassifyPost
	 * @Description: 获取点评的情感倾向
	 */
	public static CommentDetail getSentimentClassifyPost(CommentDetail comment)
			throws Exception {
		String access_token = AuthUtil.getAuth();
		String url = "https://aip.baidubce.com/rpc/2.0/nlp/v1/sentiment_classify?access_token="
				+ access_token;
		CloseableHttpClient client = HttpClientBuilder.create().build();
		HttpPost post = new HttpPost(url);
		post.setHeader("Content-type", "application/json");

		JSONObject jo = new JSONObject();
		jo.put("text", comment.getContent());

		StringEntity params = new StringEntity(jo.toString(), "GBK");
		post.setEntity(params);

		HttpResponse response = client.execute(post);
		// response
		HttpEntity entity = response.getEntity();
		String result = EntityUtils.toString(entity, "GBK").trim();
		if (StringUtils.isNotEmpty(result)) {
			JSONObject jsonObject = JSONObject.fromObject(result);
			if (jsonObject.get("items") != null) {
				com.alibaba.fastjson.JSONArray jsonArr = JSON
						.parseArray(jsonObject.get("items").toString());
				Iterator<Object> it = jsonArr.iterator();
				while (it.hasNext()) {
					com.alibaba.fastjson.JSONObject ob = (com.alibaba.fastjson.JSONObject) it
							.next();
					if (!ob.isEmpty()) {
						comment.setNegativeProb(ob
								.getFloatValue("negative_prob"));
						comment.setPositiveProb(ob
								.getFloatValue("positive_prob"));
						comment.setSenseType(ob.getString("sentiment"));
					}
					comment.setDateNum(DateUtil.getTwoDayNum(comment.getOperTime(), comment.getCreateDate()));
					Log.info(comment.getOperTime() + "------>" + comment.getCreateDate() + "相隔天数：" + DateUtil.getTwoDayNum(
							comment.getOperTime(), comment.getCreateDate()));
				}
			}
		}
		return comment;
	}
}
